package cn.kill.controller;

import cn.jbit.entity.User;
import cn.jbit.utils.JwtUtil;
import cn.jbit.utils.ResResult;
import cn.jbit.utils.Salt;
import cn.jbit.utils.StringUtil;
import cn.kill.service.UserService;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * 源码学院只为培养优秀的bat程序员而生
 *
 * @author 学员张在成
 * @data 2021/6/14
 * 这里应该改成登录LoginController
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService  userService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @GetMapping("/login")
    public ResResult  login(HttpServletRequest request, User user){

            //效验账户是否合法
            if (StringUtil.isBlank(user.getPassword())||StringUtil.isBlank(user.getUsername())){
                return new ResResult(400,"请输入您的账户或者密码",null);
            }
            //获取密码，进行密码比对
            String  encyptPwd= DigestUtils.md5Hex(Salt.SALT+user.getPassword());

            User loginUser=userService.UserInfoAsUserPwd(user.getUsername(),encyptPwd);

            if (loginUser==null){
                return new ResResult(400,"该账户不存在",null);
            }

            if (!loginUser.getPassword().equals(encyptPwd)){
                return new ResResult(401,"密码有误，请重新输入",null);
            }
            //生成token
            String token= JwtUtil.generatorToken(user.getId());

            //token存储在redis中
            redisTemplate.opsForValue().set("TOKEN"+token, JSON.toJSONString(loginUser),1, TimeUnit.DAYS);

            return new ResResult(200,"登录成功",token);
    }


    //1.前端携带token在后端效验是否合法，合法的话，在进行redis中的合法效验,获取用户的信息
    @PostMapping("/getUserInfo")
    public  ResResult  getUserAndToken(@RequestHeader("Authorization") String token){
            if (!StringUtil.isBlank(token)){
                return null;
            }
            //效验token
            Claims claims=JwtUtil.getClaimByToken(token);
            if (claims==null){
                return  null;
            }

            //判断token在redis中是否存在
            String userJson= redisTemplate.opsForValue().get("TOKEN"+token);
            if(userJson==null){
                return  null;
            }
            User user=JSON.parseObject(userJson,User.class);

            System.out.println(user.getUsername());
            return  new ResResult(200,"获取用户信息成功",user);
    }



}
